﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;

namespace Guline.Web.JXAccount.Models
{
    public class Caderer
    {
        List<CardCharge> list;
        string path;
        IFormatter formatter;
        public Caderer(string path)
        {
            
            formatter = new BinaryFormatter();
            this.path =path;
            try
            {
                this.Load();
            }
            catch
            {
                list = new List<CardCharge>();
            }
        }
        public List<CardCharge> getList()
        {
            return list;
        }
        public void Save()
        {
            Stream stream = new FileStream(this.path, FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, this.list);
            stream.Close();
        }
        public CardCharge Search(string money)
        {
            return list.Where(m => m.Money == money).FirstOrDefault();
        }
        public void Load()
        {
            
            Stream stream = new FileStream(this.path, FileMode.Open, FileAccess.Read, FileShare.Read);
            this.list= (List<CardCharge>)formatter.Deserialize(stream);
            stream.Close();
        }
        public bool Add(CardCharge model)
        {   var obj = list.Where(m=>m.Money==model.Money).FirstOrDefault();
            if (obj == null)
            {
                list.Add(model);
                return true;
            }
            return false;
        }
        public bool Edit(CardCharge model)
        {
            var obj = list.Where(m=>m.Money==model.Money).FirstOrDefault();
            if (obj != null)
            {
                obj.Xu = model.Xu;
                return true;
            }
            return false;
        }
        public bool Delete(string money)
        {
            var obj = list.Where(m => m.Money == money).FirstOrDefault();
            if (obj != null)
            {
                list.Remove(obj);
                return true;
            }
            return false;
        }
    }
}